package com.viknix.threadpool.manager.config.dump;

import com.viknix.threadpool.manager.config.event.ConfigDumpEvent;
import com.viknix.threadpool.manager.server.dependence.monitor.event.Event;
import com.viknix.threadpool.manager.server.dependence.monitor.listeners.Listener;

/**
 * @Author: Dongqi
 * @Date: 2021/11/22 10:51
 * @Version 1.0
 * @Description: Dump config subscriber.
 */
public class DumpConfigHandler extends Listener<ConfigDumpEvent> {

    /**
     * 触发配置转储事件。
     * trigger config dump event.
     *
     * @param event {@link ConfigDumpEvent}
     * @return {@code true} if the config dump task success , else {@code false}
     */
    public static boolean configDump(ConfigDumpEvent event) {
        final String dataId = event.getDataId();
        final String group = event.getGroup();
        final String namespaceId = event.getNamespaceId();
        final String content = event.getContent();
        final long lastModified = event.getLastModifiedTs();
//            if (dataId.equals(AggrWhitelist.AGGRIDS_METADATA)) {
//                AggrWhitelist.load(content);
//            }
//
//            if (dataId.equals(ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA)) {
//                ClientIpWhiteList.load(content);
//            }
//
//            if (dataId.equals(SwitchService.SWITCH_META_DATAID)) {
//                SwitchService.load(content);
//            }

        boolean result;
        if (!event.isRemove()) {
            // remove 参数为 false
            result = ConfigCacheService.dump(dataId, group, namespaceId, content, lastModified);
        } else {
            // TODO 如果直接把配置remove掉，在发布事件，那么会导致客户端报错
            // remove 参数为 true，需要将配置从内存中移除
            result = ConfigCacheService.remove(dataId, group, namespaceId);
        }
        return result;
    }

    @Override
    public void onEvent(ConfigDumpEvent event) {
        configDump(event);
    }

    @Override
    public Class<? extends Event> subscribeType() {
        return ConfigDumpEvent.class;
    }
}
